import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Input, 
  DatePicker, 
  Table, 
  Select,
  Typography,
  Space,
  message,
  Modal,
  Tag,
  Checkbox,
  Row,
  Col
} from 'antd';
import { 
  FilterOutlined,
  LeftOutlined,
  RightOutlined,
  EyeOutlined,
  CloseOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import styles from './Order.module.css';

const { Search } = Input;
const { Text } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

export default function Order() {
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [dateRange, setDateRange] = useState([]);
  const [orderStatus, setOrderStatus] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [orders, setOrders] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });



  // 获取订单数据
  const fetchOrders = async (params = {}) => {
    try {
      setLoading(true);
      
      // 检查用户是否已登录
      const currentUser = localStorage.getItem('currentUser');
      if (!currentUser) {
        console.error('用户未登录');
        return;
      }
      
      // 构建查询参数
      const queryParams = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      };
      
      // 获取token
      const token = localStorage.getItem('token');
      if (!token) {
        console.error('用户未登录或token已过期');
        return;
      }
      
      // 调用API
      const response = await fetch(`http://localhost:3001/orders?${new URLSearchParams(queryParams)}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      
      if (!response.ok) {
        if (response.status === 401) {
          console.error('获取订单列表失败: 认证失败');
          message.error('认证失败，请重新登录');
          return;
        }
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.data && result.pagination) {
        setOrders(result.data);
        setPagination({
          ...pagination,
          total: result.pagination.total
        });
      } else {
        console.error('获取订单列表失败: 响应格式错误');
        message.error('获取订单列表失败');
      }
    } catch (error) {
      message.error('获取订单列表失败');
      console.error('获取订单列表错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchOrders();
  }, []);

  // 处理筛选
  const handleFilter = () => {
    const params = {};
    if (searchText) params.searchText = searchText;
    if (orderStatus) params.orderStatus = orderStatus;
    if (dateRange && dateRange.length === 2) {
      params.startDate = dateRange[0].format('YYYY-MM-DD');
      params.endDate = dateRange[1].format('YYYY-MM-DD');
    }
    fetchOrders(params);
  };

  // 获取订单状态标签
  const getStatusTag = (status) => {
    const statusMap = {
      pending: { text: '待支付', color: 'orange' },
      paid: { text: '已支付', color: 'green' },
      closed: { text: '已关闭', color: 'red' },
      refunded: { text: '已退款', color: 'gray' }
    };
    
    const statusInfo = statusMap[status] || { text: '未知', color: 'default' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  // 获取操作按钮
  const getActionButtons = (record) => {
    const actions = [];
    
    // 查看按钮
    actions.push(
      <Button 
        key="view" 
        type="text" 
        icon={<EyeOutlined />} 
        className={styles.viewBtn}
        onClick={() => handleView(record)}
      >
        查看
      </Button>
    );
    
    // 根据状态显示不同操作
    if (record.orderStatus === 'pending') {
      actions.push(
        <Button 
          key="cancel" 
          type="text" 
          icon={<CloseOutlined />} 
          className={styles.cancelBtn}
          onClick={() => handleCancel(record)}
        >
          取消
        </Button>
      );
    } else if (record.orderStatus === 'closed' || record.orderStatus === 'refunded') {
      actions.push(
        <Button 
          key="delete" 
          type="text" 
          icon={<DeleteOutlined />} 
          className={styles.deleteBtn}
          onClick={() => handleDelete(record)}
        >
          删除
        </Button>
      );
    }
    
    return actions;
  };

  // 查看订单详情
  const handleView = async (record) => {
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`http://localhost:3001/orders/${record._id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });
      const result = await response.json();
      
      if (result.success) {
        const order = result.data;
        Modal.info({
          title: '订单详情',
          width: 600,
          content: (
            <div>
              <p><strong>订单编号：</strong>{order.orderId}</p>
              <p><strong>用户昵称：</strong>{order.userNickname}</p>
              <p><strong>手机号：</strong>{order.phone}</p>
              <p><strong>课程名称：</strong>{order.courseName}</p>
              <p><strong>订单金额：</strong>¥{order.orderAmount}</p>
              <p><strong>订单状态：</strong>{getStatusTag(order.orderStatus)}</p>
              <p><strong>提交时间：</strong>{new Date(order.submitTime).toLocaleString()}</p>
              {order.payTime && <p><strong>支付时间：</strong>{new Date(order.payTime).toLocaleString()}</p>}
              {order.closeTime && <p><strong>关闭时间：</strong>{new Date(order.closeTime).toLocaleString()}</p>}
              {order.refundTime && <p><strong>退款时间：</strong>{new Date(order.refundTime).toLocaleString()}</p>}
              {order.remark && <p><strong>备注：</strong>{order.remark}</p>}
            </div>
          )
        });
      } else {
        message.error(result.message || '获取订单详情失败');
      }
    } catch (error) {
      message.error('获取订单详情失败');
      console.error('获取订单详情错误:', error);
    }
  };

  // 取消订单
  const handleCancel = (record) => {
    Modal.confirm({
      title: '确认取消订单',
      content: `确定要取消订单 ${record.orderId} 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const token = localStorage.getItem('token');
          const response = await fetch(`http://localhost:3001/orders/${record._id}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
              orderStatus: 'closed'
            })
          });
          
          const result = await response.json();
          
          if (result.success) {
            message.success('订单已取消');
            fetchOrders();
          } else {
            message.error(result.message || '取消订单失败');
          }
        } catch (error) {
          message.error('取消订单失败');
          console.error('取消订单错误:', error);
        }
      }
    });
  };

  // 删除订单
  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除订单',
      content: `确定要删除订单 ${record.orderId} 吗？此操作不可恢复！`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          const token = localStorage.getItem('token');
          const response = await fetch(`http://localhost:3001/orders/${record._id}`, {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${token}`
            }
          });
          
          const result = await response.json();
          
          if (result.success) {
            message.success('订单已删除');
            fetchOrders();
          } else {
            message.error(result.message || '删除订单失败');
          }
        } catch (error) {
          message.error('删除订单失败');
          console.error('删除订单错误:', error);
        }
      }
    });
  };

  // 表格列定义
  const columns = [
    {
      title: '订单编号',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 120,
      fixed: 'left'
    },
    {
      title: '用户昵称',
      dataIndex: 'userNickname',
      key: 'userNickname',
      width: 120
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120
    },
    {
      title: '课程名称',
      dataIndex: 'courseName',
      key: 'courseName',
      width: 200
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      key: 'orderAmount',
      width: 100,
      render: amount => `¥${amount}`
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      key: 'orderStatus',
      width: 100,
      render: status => getStatusTag(status)
    },
    {
      title: '提交时间',
      dataIndex: 'submitTime',
      key: 'submitTime',
      width: 150
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (text, record) => (
        <Space size="middle">
          {getActionButtons(record)}
        </Space>
      )
    }
  ];

  // 分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
  };

  return (
    <div className={styles.orderContainer}>
      {/* 订单筛选 */}
      <Card 
        title="订单筛选" 
        bordered={false} 
        className={styles.filterCard}
      >
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <div className={styles.filterItem}>
              <span className={styles.filterLabel}>订单状态：</span>
              <Select
                placeholder="请选择"
                style={{ width: '100%' }}
                value={orderStatus}
                onChange={setOrderStatus}
                allowClear
              >
                <Option value="pending">待支付</Option>
                <Option value="paid">已支付</Option>
                <Option value="closed">已关闭</Option>
                <Option value="refunded">已退款</Option>
              </Select>
            </div>
          </Col>
          
          <Col span={8}>
            <div className={styles.filterItem}>
              <span className={styles.filterLabel}>提交时间：</span>
              <RangePicker 
                style={{ width: '100%' }}
                value={dateRange}
                onChange={setDateRange}
              />
            </div>
          </Col>
          
          <Col span={8}>
            <Search
              placeholder="请输入订单号、用户账号、昵称"
              allowClear
              style={{ width: '100%' }}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={handleFilter}
            />
          </Col>
          
          <Col span={2}>
            <Button 
              type="primary" 
              icon={<FilterOutlined />}
              onClick={handleFilter}
              loading={loading}
              style={{ width: '100%' }}
            >
              筛选
            </Button>
          </Col>
        </Row>
      </Card>
      
      {/* 订单列表 */}
      <Card 
        title="订单列表" 
        bordered={false} 
        className={styles.listCard}
      >
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="_id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            showTotal: total => `共 ${total} 条`,
            itemRender: (page, type, originalElement) => {
              if (type === 'prev') return <LeftOutlined />;
              if (type === 'next') return <RightOutlined />;
              return originalElement;
            }
          }}
          scroll={{ x: 1200 }}
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
} 